#this provides a function to read a SPARC program into parts S, P, and R

def getParts(program):
	state = -1
	sortdefs =[]
	sortdecs =[]
	prules = []
	strbuffer = ''
	i = 0
	for line in program:
		i+=1
		#remove whitespace
		nline = line.strip()
		#ignore comments
		if nline.find('%%',0) == 0:
			continue
		#ignore blank strings
		if len(nline) == 0:
			continue
		#set states
		if nline == 'sorts definition':
			if state != -1:
				raise Exception('Syntax error')
			state = 0;
			continue
		if nline == 'predicates declaration':
			if state != 0:
				raise Exception('Syntax error')
			state = 1;
			continue
		if nline == 'program rules':
			if state != 1:
				raise Exception('Syntax error')
			state = 2;
			continue
		#read strings
		if state == 0:
			sortdefs.append((i,nline)) 
		if state == 1:
			sortdecs.append((i,nline)) 
		if state == 2:
			if nline.endswith('.'):
				if len(strbuffer) == 0:
					prules.append((i,nline))
				else:
					prules.append((i,strbuffer+nline))
					strbuffer = ''
			else:
				strbuffer = strbuffer+nline
		#end for
	#exit conditions
	if state != 2 or len(strbuffer) != 0:
		raise Exception('Syntax error')
	return (sortdefs, sortdecs, prules, i)
